<script setup lang="ts">
import type {
  CaseHistoryForm,
  MedicalFileType,
} from '#/api/business/case-history/model';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { isNumber } from 'lodash-es';

import { useVbenForm } from '#/adapter/form';
import {
  caseHistoryAdd,
  caseHistoryDetail,
  caseHistoryUpdate,
} from '#/api/business/case-history';
import { uploadApiNew } from '#/api/core/upload';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { modalSchema } from './data';

const emit = defineEmits<{ reload: [] }>();

const id = ref<number>();
const title = computed(() => {
  return isNumber(id.value) ? $t('pages.common.edit') : $t('pages.common.add');
});

const medicalFile = ref<MedicalFileType>();
const handleUpload = (file: File) => {
  uploadApiNew({
    file,
    onSuccess: (data) => {
      medicalFile.value = {
        originalFileName: data.originalFilename,
        fileName: data.objectName,
        filePath: data.url,
      };
    },
  });
};
const handleRemove = () => {
  medicalFile.value = undefined;
};

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  schema: modalSchema(handleUpload, handleRemove),
  showDefaultActions: false,
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  class: 'w-[550px]',
  fullscreenButton: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { id: idValue } = modalApi.getData();
    id.value = idValue;

    if (idValue) {
      const { medicalFile: medicalFileValue, ...rest } =
        await caseHistoryDetail(idValue);
      let newMedicalFile;

      // 处理病历文件显示
      if (medicalFileValue) {
        const fileData = cloneDeep(medicalFileValue);
        newMedicalFile = [
          {
            uid: fileData.id,
            name: fileData.fileName,
            status: 'done',
            url: fileData.filePath,
          },
        ];
        medicalFile.value = {
          originalFileName: fileData.originalFileName,
          fileName: fileData.fileName,
          filePath: fileData.filePath,
        };
      }

      await formApi.setValues({
        ...rest,
        medicalFile: newMedicalFile,
      });
    }
    await markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const { medicalFile: _medicalFile, ...rest } = await formApi.getValues();
    const data: CaseHistoryForm = cloneDeep(rest as CaseHistoryForm);

    // 设置病历文件参数
    data.medicalFileParam = medicalFile.value;

    await (id.value
      ? caseHistoryUpdate({ id: id.value, ...data })
      : caseHistoryAdd(data));
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title">
    <BasicForm />
  </BasicModal>
</template>
